package org.company.mercury.controller;

import org.company.venus.bean.User;
import org.company.venus.dao.hibernate.BaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("user")
public class UserController {
    
    @Autowired
    private BaseDao<User> userDao;
    
    @ModelAttribute
    public User setUser(@RequestParam String username,
            @RequestParam String password,
            @RequestParam(required=false) String email,
            @RequestParam(required=false) Integer age,
            @RequestParam(required=false) Integer sex,
            @RequestParam(required=false) Double salary){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setAge(age);
        user.setSex(sex);
        user.setSalary(salary);
        return user;
    }

    @RequestMapping("/register")
    public String register (@ModelAttribute User user,
            Model model){
        System.out.println("username == " + user.getUsername());
        System.out.println("password == " + user.getPassword());
        System.out.println("email == " + user.getEmail());
        System.out.println("age == " + user.getAge());
        System.out.println("sex == " + user.getSex());
        System.out.println("salary == " + user.getSalary());
        
        userDao.save(user);
        return "redirect:/login.html";
    }
    
    
    @RequestMapping("/login")
    public String login(@RequestParam String username,
            @RequestParam  String password,
            Model model) {
        System.out.println("username == " + username);
        User user = userDao.get(User.class,username);
        if(user == null) {
            model.addAttribute("retCode", "0010");
            model.addAttribute("retMsg","用户名不存在，请先注册");
            return "redirect:/html/login.html";
        } else if(!user.getPassword().equals(password)){
            model.addAttribute("retCode", "0011");
            model.addAttribute("retMsg","密码不正确，请重新输入");
            return "redirect:/html/login.html";
        }
        return "redirect:/npage/main.html";
    }
}
